import 'dart:io';

import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/env/common_config.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/conform_dialog.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/modules/me/application/notification/app_update_info_notifier.dart';
import 'package:casdon/modules/me/application/notification/app_version_info_service.dart';

import 'package:casdon/modules/me/ui/widgets/form_field_item.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:url_launcher/url_launcher.dart';

@RoutePage()
class AppAboutScreen extends ConsumerWidget {
  const AppAboutScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final state = ref.watch(appVersionProvider);
    return Scaffold(
      appBar: CommonAppBar(title: "关于凯度生活家"),
      body: Container(
        color: context.colorScheme.surface,
        child: Column(
          children: [
            SizedBox(height: 52.h),
            SizedBox(
              width: 56, // 固定宽度
              height: 56, // 固定高度
              child: AspectRatio(
                aspectRatio: 1,
                child: Image(
                  image: AssetImage(Assets.images.appAbout.path),
                  fit: BoxFit.cover, // 覆盖整个区域（可能裁剪）
                ),
              ),
            ),
            SizedBox(height: 5.h),
            Text(
              "凯度生活家",
              style: context.textTheme.headlineLarge?.copyWith(
                color: context.customColorThemeNonNull.textColor1,
              ),
            ),
            SizedBox(height: 5.h),
            Consumer(
              builder: (_, ref, __) {
                final version = ref.watch(appVersionProvider).value;
                return Text(
                  "版本: v${version?.version ?? '--'}",
                  style: context.textTheme.bodyMedium?.copyWith(
                    color: context.customColorThemeNonNull.textColor3,
                  ),
                );
              },
            ),
            SizedBox(height: 48.h),
            FormFieldItem(
              label: ' 检查更新',
              isRequired: false,
              isEditable: false,
              showArrow: true,
              backgroundColor: Colors.white,
              onTap: () => _checkUpdate(context, ref),
            ),
            FormFieldItem(
              label: '《隐私政策》',
              isRequired: false,
              isEditable: false,
              showArrow: true,
              backgroundColor: Colors.white,
              onTap: () => _goPrivacyPolicy(context, ref),
            ),
            FormFieldItem(
              label: '《用户协议》',
              isRequired: false,
              isEditable: false,
              showArrow: true,
              showBottomDivider: false,
              backgroundColor: Colors.white,
              onTap: () => _goUserAgreement(context, ref),
            ),
          ],
        ),
      ),
    );
  }

  void _checkUpdate(BuildContext context, WidgetRef ref) async {
    await _maybeShowAppUpdateDialog(context, ref);
  }

  Future<void> _maybeShowAppUpdateDialog(
    BuildContext context,
    WidgetRef ref,
  ) async {
    final upadateRet = await ref.read(appUpdateInfoProvider.future);
    if (!context.mounted) {
      return;
    }
    final info = upadateRet['data'] as Map<String, dynamic>?;
    if (info == null) {
      return;
    }
    final bool bUpdate = info['isUpdate'] as bool? ?? false;
    final versionInfo = info['versionInfo'] as Map<String, dynamic>?;

    if (!bUpdate || versionInfo == null) {
      ToastUtil.show("当前已是最新版本");
      return;
    }

    final content = versionInfo['content'] as String? ?? '';

    final ret = await showCustomConfirmDialog(
      context: context,
      title: "有新版本更新",
      content: content,
      confirmText: "去更新",
      confirmAction: () async => _openAppStore(),
      contentAlignment: TextAlign.left,
      cancelText: "取消",
    );

    if (!context.mounted) {
      return;
    }

    if (ret ?? false) {
      await _openAppStore();
    }
  }

  Future<void> _openAppStore() async {
    final appUrl = CommonConfig.app_store_url;

    final uri = Uri.tryParse(appUrl);
    if (uri == null) {
      Log.w('无效的 App Store 链接: $appUrl');
      return;
    }

    final launched = await launchUrl(uri, mode: LaunchMode.externalApplication);
    if (!launched) {
      Log.w('无法打开 App Store 链接: $appUrl');
    }
  }

  void _goPrivacyPolicy(BuildContext context, WidgetRef ref) {
    WebPageRoute(
      url: CommonConfig.privacy_protocol,
      title: "隐私政策",
    ).push(context);
  }

  void _goUserAgreement(BuildContext context, WidgetRef ref) {
    WebPageRoute(url: CommonConfig.urser_protocol, title: "用户协议").push(context);
  }
}
